﻿using UnityEngine;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using System;
namespace GameEditor
{
    public class MapsWindow : BaseWidget
    {
        public GameObject ItemPrefab;
        public Transform MapsGridView;

        public GameObject EnterEditMap;
        public GameObject NewGameMapButton;

        public int SelectMapIndex = -1;


        public NewMapWindow NewMapWindow;
        public override void OnLoad()
        {
            FillMapsView();

            IDictionaryEnumerator iter = MapTableMgr.MapIndexTable.GetEnumerator();
            if (iter.MoveNext())
            {
                SelectMapItem((int)iter.Key);
            }

            UIEventListener.Get(EnterEditMap).onClick = OnClickEnterEditorGame;
            UIEventListener.Get(NewGameMapButton).onClick = this.OnClickNewGameMap;
        }

        public void FillMapsView()
        {
            foreach (DictionaryEntry mapItem in MapTableMgr.MapIndexTable)
            {
                Hashtable MapTable = (Hashtable)mapItem.Value;
                GameObject NewItem = NGUITools.AddChild(MapsGridView.gameObject, ItemPrefab);
                NewItem.transform.Find("MapDesc").GetComponent<UILabel>().text = (string)MapTable[":desc"];
                NewItem.transform.Find("FileName").GetComponent<UILabel>().text = (string)MapTable[":map-path"];
                NewItem.SetActive(true);
                NewItem.name = mapItem.Key.ToString();
                UIEventListener.Get(NewItem).onClick = OnClickMapItem;
            }
        }

        public void OnClickEnterEditorGame(GameObject go)
        { 
            GameEditor.UI.Close("MapsWindow");
            GameEditor.Scene.LoadScene<MapEditorScene>(SelectMapIndex);
        }

        public void OnClickMapItem(GameObject go)
        {
            SelectMapItem(int.Parse(go.name));
        }

        public void SelectMapItem(int id)
        {
            if (SelectMapIndex != -1)
            {
                MapsGridView.Find(SelectMapIndex.ToString()).GetComponent<UISprite>().color = Color.white;
            }
            MapsGridView.Find(id.ToString()).GetComponent<UISprite>().color = Color.green;
            SelectMapIndex = id;
        }

        public void OnClickNewGameMap(GameObject go)
        {
            this.NewMapWindow.gameObject.SetActive(true);
            /*
                Trigger
             
             */
        }
    }

}